package com.nf.health.app;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.IBinder;
import android.os.StrictMode;
import android.support.multidex.MultiDex;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.baidu.mapapi.SDKInitializer;
import com.hyphenate.easeui.controller.EaseUI;
import com.hyphenate.easeui.domain.EaseUser;
import com.lling.photopicker.LibApplication;
import com.nf.health.app.db.DbManager;
import com.nf.health.app.http.HttpStringRequest;
import com.nf.health.app.models.UserInfo;
import com.nf.health.app.utils.CrashHandler;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.umeng.analytics.MobclickAgent;

import cn.bluetools.BluetoothLeService;
import cn.bluetools.Pedometer_TypeInfo;
import cn.jpush.android.api.JPushInterface;


/**
 * 需要使用photopicker，需继承次Application
 */
public class MyApplication extends LibApplication {
    private static MyApplication mInstance;
    private static RequestQueue requestQueue;
    public static DisplayImageOptions optionsHead;
    public static DisplayImageOptions optionsPic;
    private RefWatcher refWatcher;
    private static final String TAG = "MyApplication";
    private final boolean IS_DEBUG = false;
    public static BluetoothLeService mBluetoothLeService; // 蓝牙服务类
    public static ServiceConnection mServiceConnection;

    public static RefWatcher getRefWatcher(Context context) {
        MyApplication application = (MyApplication) context.getApplicationContext();
        return application.refWatcher;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        SDKInitializer.initialize(this);
        JPushInterface.setDebugMode(IS_DEBUG); // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this); // 初始化 JPush

        CrashHandler.getInstance().init(this);

        LogUtil.openDebugLog(IS_DEBUG);

//		Logger.init();
//		Logger.init("NF_APP");                 // default PRETTYLOGGER or use just init()
//				.methodCount(3)                 // default 2
        // .hideThreadInfo()               // default shown
//                .logLevel(LogLevel.NONE)        // default LogLevel.FULL
//                .methodOffset(2)                // default 0
//				.logTool(new AndroidLogTool()); // custom log tool, optional


        EaseUI.getInstance().init(this, null);
        EaseUI.getInstance().setUserProfileProvider(new EaseUI.EaseUserProfileProvider() {
            @Override
            public EaseUser getUser(String username) {
                //复写环信获取EaseUser的方法,这样本地保存的信息(昵称,头像等)就可以在easeui中得到
                return getUserInfo(username);
            }
        });

        //内存泄露分析
        refWatcher = LeakCanary.install(this);

        requestQueue = Volley.newRequestQueue(this);
        initImageLoader();

        //
        if (LogUtil.IS_DEBUG) {
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectDiskReads()
                    .detectDiskWrites()
                    .detectNetwork()
                    .penaltyLog()
                    .build());
        }

        //友盟统计
        MobclickAgent.setDebugMode(false); //发布时候设置为false
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
        bindLeService();
    }

    private EaseUser getUserInfo(String username) {
        if (username.equals(PreferenceHelper.getUser().getUserid())) {
//            return UserProfileManager.getUserProfileManager().getCurrentUserInfo();
            //返回当前用户,从UserInfo中取得信息,UserInfo在修改照片后能够及时更新
            UserInfo info = PreferenceHelper.getUser();
            EaseUser easeUser = new EaseUser(info.getUserid());
            easeUser.setNick(info.getNick());
            easeUser.setAvatar(info.getHimg());
            return easeUser;
        } else {
//            return com.nf.health.app.AppModel.getInstatnce().getContactList().get(username);
            return DbManager.getInstance().getContact(username);
        }

    }

    public static RequestQueue getRequestQueue() {
        return requestQueue;
    }

    public static MyApplication getInstance() {
        return mInstance;
    }

    /**
     * {@link HttpStringRequest }128行
     *
     * @return
     */
    public static String getNF_USER_SESSION() {
        return PreferenceHelper.getString(PreferenceHelper.NF_USER_SESSION, "");
    }

    /**
     * 正式用户登录的token值
     *
     * @return
     */
    public static String getToken() {
        return PreferenceHelper.getString(PreferenceHelper.TOKEN, "");
    }

    @SuppressWarnings("deprecation")
    private void initImageLoader() {
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .threadPoolSize(3)
                // default
                .threadPriority(Thread.NORM_PRIORITY - 1)
                // default
                .tasksProcessingOrder(QueueProcessingType.FIFO)

                // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
                .memoryCacheSize(2 * 1024 * 1024).memoryCacheSizePercentage(13) // default
                .discCacheSize(50 * 1024 * 1024) // 缓冲大小
                .discCacheFileCount(100) // 缓冲文件数目
                .discCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
                .imageDownloader(new BaseImageDownloader(this)) // default
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                .writeDebugLogs().build();

        // 2.单例ImageLoader类的初始化
        ImageLoader imageLoader = ImageLoader.getInstance();
//        imageLoader.init(config);

        imageLoader.init(config);
        optionsHead = new DisplayImageOptions.Builder()
                .showStubImage(R.drawable.my_family_icon)            // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.my_family_icon)    // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.my_family_icon)        // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565)            // 默认是ARGB_8888， 使用RGB_565会比使用ARGB_8888少消耗2倍的内存
                .cacheInMemory(true)                            // 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true)
                .imageScaleType(ImageScaleType.IN_SAMPLE_INT)
                .cacheOnDisc(true)                                // 设置下载的图片是否缓存在SD卡中
                .build();
        optionsPic = new DisplayImageOptions.Builder()
                .showStubImage(R.drawable.default_image)            // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.default_image)    // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.default_image)        // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565)            // 默认是ARGB_8888， 使用RGB_565会比使用ARGB_8888少消耗2倍的内存
                .cacheInMemory(true)                            // 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true)
                .imageScaleType(ImageScaleType.IN_SAMPLE_INT)
                .cacheOnDisc(true)                                // 设置下载的图片是否缓存在SD卡中
                .build();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);//按照stackoverflow方法,解决jsoup问题,是方法数超过65535?
    }


    private void bindLeService() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            return;
        }
        mServiceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName,
                                           IBinder service) {
                mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
                Constants.mBluetoothLeService = mBluetoothLeService;
                BluetoothLeService.setPedometerType(Pedometer_TypeInfo.Pedometer_Type.L28T);
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                mBluetoothLeService = null;
            }
        };

        Intent bleService = new Intent(this, BluetoothLeService.class);
        bindService(bleService, mServiceConnection, Context.BIND_AUTO_CREATE);
    }
}
